// src/pages/VMDetail/ConsoleTab.tsx
import React, { useState, useEffect } from 'react';
import { Card, Tabs, Alert, Spin, Button } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { consoleApi } from '../../api/console';
import SerialConsole from '../../components/Console/SerialConsole';
import VNCConsole from '../../components/Console/VNCConsole';

interface ConsoleTabProps {
  vmName: string;
  connectionId?: string;
}

const ConsoleTab: React.FC<ConsoleTabProps> = ({ vmName, connectionId = 'default' }) => {
  const [availableTypes, setAvailableTypes] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeConsole, setActiveConsole] = useState<string>('serial');

  useEffect(() => {
    loadConsoleTypes();
  }, [vmName, connectionId]);

  const loadConsoleTypes = async () => {
    try {
      setLoading(true);
      const types = await consoleApi.getConsoleTypes(vmName, connectionId);
      setAvailableTypes(types);
      if (types.length > 0 && !types.includes(activeConsole)) {
        setActiveConsole(types[0]);
      }
    } catch (error) {
      console.error('Failed to load console types:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (availableTypes.length === 0) {
    return (
      <Alert
        message="无可用控制台"
        description="该虚拟机没有配置任何控制台设备。"
        type="warning"
        showIcon
      />
    );
  }

  const consoleItems = [
    availableTypes.includes('serial') && {
      key: 'serial',
      label: '串行控制台',
      children: <SerialConsole vmName={vmName} connectionId={connectionId} />,
    },
    availableTypes.includes('vnc') && {
      key: 'vnc',
      label: 'VNC',
      children: <VNCConsole vmName={vmName} connectionId={connectionId} />,
    },
    availableTypes.includes('spice') && {
      key: 'spice',
      label: 'SPICE',
      children: (
        <Alert
          message="SPICE 控制台"
          description="SPICE 控制台支持待实现"
          type="info"
          showIcon
        />
      ),
    },
  ].filter(Boolean);

  return (
    <Card
      extra={
        <Button icon={<ReloadOutlined />} onClick={loadConsoleTypes}>
          刷新
        </Button>
      }
    >
      <Tabs
        activeKey={activeConsole}
        onChange={setActiveConsole}
        items={consoleItems as any}
      />
    </Card>
  );
};

export default ConsoleTab;
